package cn.su.servlet;

import cn.su.pojo.User;
import cn.su.service.UserService;
import cn.su.service.impl.Userserviceimpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UserLogin", value = "/login.do")
public class UserLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

       // response.setContentType("text/html;charset=UTF-8");
          //问题一：这里用 request.setCharacterEncoding("utf-8");才可以解决获取乱码
        //用 response.setContentType("text/html;charset=UTF-8"); 不行
        //setContentType 不是包括setCharacterEncoding
        // 和 response.setHeader("Content-Type","text/html;charset=UTF-8");
        String userCode = request.getParameter("userCode");
        String password = request.getParameter("userPassword");
     //System.out.println(userCode+"---用户---");
       if (userCode==null||password==null){
           //重定向
           response.sendRedirect("login.jsp");
       }else {
           UserService userService=new Userserviceimpl();
           User user = userService.Login(userCode, password);
             if (user==null){
                 request.setAttribute("error","  请输入正确的账号密码！");
                 request.getRequestDispatcher("login.jsp").forward(request,response);
             }else{
                 ServletContext context=request.getServletContext();
                 context.setAttribute("userName",user.getUserName());
                request.getSession().setAttribute("user",user);
                 request.getRequestDispatcher("jsp/frame.jsp").forward(request,response);
             }
       }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
